
Imports System.Xml
Imports System.Web

Imports System.Collections.Generic
Imports DotNetNuke.Services
Imports DotNetNuke.Services.Cache
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.Localization
Imports DotNetNuke.UI.WebControls
Imports DotNetNuke.Entities.Host
Imports DotNetNuke.Entities.Portals
Imports DotNetNuke.Common
Imports DotNetNuke.Common.Utilities
Imports DotNetNuke.Framework.Providers
Imports Telerik.Web.UI

Namespace dnnWerk.Providers.RadEditorProvider

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' </history>
    Partial Class SaveTemplate
        Inherits DotNetNuke.Framework.PageBase


#Region "Event Handlers"

        Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

            DotNetNuke.Framework.AJAX.RegisterScriptManager()

            If Request.IsAuthenticated = True Then
                Response.Cache.SetCacheability(Web.HttpCacheability.ServerAndNoCache)
            End If

        End Sub

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try

                SetResStrings()

                If Not IsPostBack Then

                    FixAllowedExtensions()

                    Dim portalID As Integer = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().PortalId
                    Dim folders As ArrayList = DotNetNuke.Common.Utilities.FileSystemUtils.GetFoldersByUser(portalID, True, True, "Add")

                    'filter out only folders below the editor's template path
                    Dim strStartFolder As String = ""
                    Try
                        strStartFolder = Request.QueryString("path")
                    Catch
                    End Try
                    Dim tmpFolders As New ArrayList
                    For Each folder As DotNetNuke.Services.FileSystem.FolderInfo In folders
                        If folder.FolderPath.StartsWith(strStartFolder) Then
                            tmpFolders.Add(folder)
                        End If
                    Next

                    If tmpFolders.Count = 0 Then
                        msgError.InnerHtml = GetString("msgNoFolders.Text")
                        divInputArea.Visible = False
                        cmdClose.Visible = True
                    Else
                        FolderList.Items.Clear()

                        FolderList.DataTextField = "FolderPath"
                        FolderList.DataValueField = "FolderPath"
                        FolderList.DataSource = tmpFolders
                        FolderList.DataBind()

                        Dim rootFolder As RadComboBoxItem = FolderList.FindItemByText(String.Empty)
                        If rootFolder IsNot Nothing Then
                            rootFolder.Text = GetString("lblRootFolder.Text")
                        End If

                    End If
                End If
            Catch ex As Exception
                DotNetNuke.Services.Exceptions.LogException(ex)
                Throw ex
            End Try
        End Sub

        Protected Sub Save_OnClick(ByVal sender As Object, ByVal e As EventArgs)
            Try
                If FolderList.Items.Count = 0 Then
                    Exit Sub
                End If

                Dim portalSettings As DotNetNuke.Entities.Portals.PortalSettings = DotNetNuke.Entities.Portals.PortalSettings.Current

                Dim fileContents As String = htmlText2.Text.Trim()
                Dim newFileName As String = FileName.Text
                If Not newFileName.EndsWith(".html") Then
                    newFileName = newFileName & ".html"
                End If

                Dim rootFolder As String = portalSettings.HomeDirectoryMapPath
                Dim dbFolderPath As String = FolderList.SelectedValue
                Dim virtualFolder As String = FileSystemValidation.ToVirtualPath(dbFolderPath)
                rootFolder = rootFolder + FolderList.SelectedValue
                rootFolder = rootFolder.Replace("/", "\")

                Dim errorMessage As String = String.Empty
                Dim folderCtrl As New FileSystem.FolderController()
                Dim folder As FileSystem.FolderInfo = folderCtrl.GetFolder(portalSettings.PortalId, dbFolderPath, False)

                If (IsNothing(folder)) Then
                    ShowSaveTemplateMessage(GetString("msgFolderDoesNotExist.Text"))
                    Return
                End If

                ' Check file name is valid
                Dim dnnValidator As FileSystemValidation = New FileSystemValidation()
                errorMessage = dnnValidator.OnCreateFile(virtualFolder + newFileName, fileContents.Length)
                If (Not String.IsNullOrEmpty(errorMessage)) Then
                    ShowSaveTemplateMessage(errorMessage)
                    Return
                End If

                Dim fileCtrl As New FileSystem.FileController()
                Dim existingFile As DotNetNuke.Services.FileSystem.FileInfo = fileCtrl.GetFile(newFileName, portalSettings.PortalId, folder.FolderID)

                ' error if file exists
                If (Not Overwrite.Checked AndAlso Not IsNothing(existingFile)) Then
                    ShowSaveTemplateMessage(GetString("msgFileExists.Text"))
                    Return
                End If

                Dim newFile As FileSystem.FileInfo = existingFile
                If (IsNothing(newFile)) Then
                    newFile = New FileSystem.FileInfo()
                End If

                newFile.FileName = newFileName
                newFile.ContentType = "text/plain"
                newFile.Extension = "html"
                newFile.Size = fileContents.Length
                newFile.FolderId = folder.FolderID

                errorMessage = DotNetNuke.Common.Utilities.FileSystemUtils.CreateFileFromString(rootFolder, newFile.FileName, fileContents, newFile.ContentType, String.Empty, False)

                If (Not String.IsNullOrEmpty(errorMessage)) Then
                    ShowSaveTemplateMessage(errorMessage)
                    Return
                End If

                existingFile = fileCtrl.GetFile(newFileName, portalSettings.PortalId, folder.FolderID)
                If (newFile.FileId <> existingFile.FileId) Then
                    newFile.FileId = existingFile.FileId
                End If

                If (newFile.FileId <> Null.NullInteger) Then
                    fileCtrl.UpdateFile(newFile.FileId, newFile.FileName, newFile.Extension, newFile.Size, newFile.Width, newFile.Height, newFile.ContentType, folder.FolderPath, folder.FolderID)
                Else
                    fileCtrl.AddFile(portalSettings.PortalId, newFile.FileName, newFile.Extension, newFile.Size, newFile.Width, newFile.Height, newFile.ContentType, folder.FolderPath, folder.FolderID, True)
                End If

                ShowSaveTemplateMessage(String.Empty)
            Catch ex As Exception
                DotNetNuke.Services.Exceptions.LogException(ex)
                Throw ex
            End Try
        End Sub

#End Region

#Region "Properties"

#End Region

#Region "Methods"

        Private Sub FixAllowedExtensions()

            Dim blnHTML As Boolean = True

            Dim validExtensions As String = DotNetNuke.Entities.Host.Host.FileExtensions.ToLowerInvariant()

            If ("," + validExtensions + ",").IndexOf(",html,") = -1 Then
                blnHTML = False
            End If

            If blnHTML = False Then
                validExtensions = AddComma(validExtensions) & "html"
                Dim ctl As New HostSettingsController
                ctl.UpdateHostSetting("FileExtensions", validExtensions)
                Config.Touch()
            End If

        End Sub

        Private Function AddComma(ByVal strExpression As String)
            If strExpression.EndsWith(",") Then
                Return strExpression
            Else
                Return strExpression & ","
            End If
        End Function

        Private Sub ShowSaveTemplateMessage(ByVal errorMessage As String)
            If errorMessage = String.Empty Then
                msgSuccess.Visible = True
                msgError.Visible = False
            Else
                msgSuccess.Visible = False
                msgError.Visible = True
                msgError.InnerHtml += errorMessage
                DotNetNuke.Services.Exceptions.Exceptions.LogException(New FileManagerException("Error creating htmtemplate file [" & errorMessage & "]"))
            End If

            divInputArea.Visible = False
            cmdClose.Visible = True
        End Sub

        Private Sub SetResStrings()
            Me.lblTitle.Text = GetString("lblDialogTitle")
            Me.lblFolders.Text = GetString("lblFolders.Text")
            Me.lblFileName.Text = GetString("lblFileName.Text")
            Me.lblOverwrite.Text = GetString("lblOverwrite.Text")
            Me.cmdSave.Text = GetString("cmdSave.Text")
            Me.cmdCancel.Text = GetString("cmdCancel.Text")
            Me.cmdClose.Text = GetString("cmdClose.Text")
            Me.msgSuccess.InnerHtml = GetString("msgSuccess.Text")
            Me.msgError.InnerHtml = GetString("msgError.Text")
        End Sub

        Public Function GetString(ByVal key As String) As String
            Dim resourceFile As String = System.IO.Path.Combine(Me.TemplateSourceDirectory & "/", DotNetNuke.Services.Localization.Localization.LocalResourceDirectory & "/SaveTemplate.resx")
            Return DotNetNuke.Services.Localization.Localization.GetString(key, resourceFile)
        End Function


#End Region


    End Class

End Namespace
